from pynput import keyboard  # 导入键盘类
from playsound import playsound  # 导入palysound音乐播放包
import threading  # 导入线程包


# 定义音乐播放函数
def music(num):
    playsound(r"musics\piano{0}.mp3".format(str(num)))


# 定义按键监听函数
def on_press(key):
    '按下按键时执行。'
    try:
        # 判断按下的键的字符是否ASCII码在97-122，即A-Z
        if ord(key.char) - 96 >= 1 and ord(key.char) - 96 <= 26:
            num = ord(key.char) - 96  # 将字符对应数值放入变量num中，即字符的ASCII-96
            t = threading.Thread(target=music, args=(num,))  # 定义线程，目标为音乐函数，参数是num
            t.start()  # 运行线程，目的是为了让音乐可以同步执行多个琴音
        else:
            pass#非a-z大写按键直接跳过
    except AttributeError:
        # 特殊按键非字母数字之类的
        print('special key {0} pressed'.format(
            key))
    # 通过属性判断按键类型。


def on_release(key):
    '松开按键时执行。'
    if key == keyboard.Key.esc:
        # Stop listener
        return False
    else:
        pass


if __name__ == '__main__':
    # Collect events until released
    with keyboard.Listener(
            on_press=on_press,
            on_release=on_release) as listener:
        listener.join()
